package org.gongliang.controller.sys;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.gongliang.common.annotation.KLog;
import org.gongliang.common.base.BaseController;
import org.gongliang.common.base.Result;
import org.gongliang.common.exception.ExceptionEnum;
import org.gongliang.entity.sys.Dictionary;
import org.gongliang.kit.web.WebKit;
import org.gongliang.service.sys.DictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
* @desc   控制器
* @author 龚亮
* @version 1.0
* @date 2017年05月15日 02:52:17
*/
@Controller
@RequestMapping("/sys_dictionary")
public class DictionaryController extends BaseController {

	@RequiresPermissions("sys:dictionary:view")
	@GetMapping("/main")
	public String main() {
		return "sys/Dictionary/main";
	}

	@GetMapping("/updatePage")
	public String updatePage() {
		return "sys/Dictionary/dict";
	}

    @Autowired
    private DictionaryService dictionaryService;

	@ResponseBody
	@RequestMapping(value = "/findAll", method = { RequestMethod.GET, RequestMethod.POST })
	public Result findAll(HttpServletRequest request) {
		Map<String, Object> reqMap = WebKit.getParams(request);
		List<Dictionary> list = dictionaryService.findAll(reqMap);
		Result result = Result.success();
		result.setResData(list, list.size() + 0L);
		return result;
	}

	/**
	 * 添加或者修改 主键id不为空时更新,否则保存
	 */
	@KLog("字典管理->添加或修改字典")
	@RequiresPermissions({ "sys:dict:create", "sys:dict:update" })
	@ResponseBody
	@RequestMapping(value = "/saveORupdate", method = RequestMethod.POST)
	public Result saveORupdate(Dictionary dictionary) {
		if (dictionary == null) {
			return Result.error(ExceptionEnum.PARAM_NOT_NULL);
		}
		if (dictionary.getId() == null) {
			return dictionaryService.save(dictionary) ? Result.success("保存字典信息成功!") : Result.error("保存字典信息失败!");
		} else {
			return dictionaryService.updateById(dictionary) ? Result.success("更新字典信息成功!") : Result.error("更新字典信息失败!");
		}
	}

	/**
	 * 根据id删除
	 */
	@KLog("ap字典理->删除字典")
	@RequiresPermissions("sys:dict:delete")
	@ResponseBody
	@RequestMapping(value = "/deleteByIds", method = RequestMethod.POST)
	public Result deleteByIds(@RequestParam(value = "ids[]", required = true) String[] ids) {
		if (ids == null || ids.length == 0) {
			return Result.error(ExceptionEnum.IDS_NOT_NULL);
		}
		return dictionaryService.deleteByIds(ids) ? Result.success("删除字典成功!") : Result.error("删除字典失败!");
	}
}
